package zsy.test.java.lang;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangshuaiyin
 * @date 2022/6/8 22:14
 */
@SuppressWarnings("ALL")
public class ThreadStateDemo {
    public static void main(String[] args) {
        new Thread(new TimeWaiting(), "TimeWaitingThread").start();
        new Thread(new Waiting(), "WaitingThread").start();
        // 使用两个 Blocked 线程，一个获取锁成功，另一个被阻塞
        new Thread(new Blocked(), "BlockedThread-1").start();
        new Thread(new Blocked(), "BlockedThread-2").start();
        new Thread(new Running(), "RunningThread").start();
    }

    /**
     * 该线程不停休眠
     */
    static class TimeWaiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                sleep(100);
            }
        }
    }

    /**
     * 该线程在 Waiting.class 实例上等待
     */
    static class Waiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (Waiting.class) {
                    try {
                        Waiting.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 该线程在 Blocked.class 实例上加锁后不会释放锁
     */
    static class Blocked implements Runnable {
        @Override
        public void run() {
            synchronized (Blocked.class) {
                sleep(100);
            }
        }
    }

    /**
     * 该线程在 Blocked.class 实例上加锁后不会释放锁
     */
    static class Running implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (Running.class) {
                    System.out.println(new Random().nextInt());
                }
            }
        }
    }

    static void sleep(long timeout) {
        try {
            TimeUnit.SECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
